package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import longrise.phone.com.bjjt_henan.Adapter.AccidentLoadPicAdapter;
import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;
import longrise.phone.com.bjjt_henan.widget.PromptDialog;

/**
 * 上传事故照片界面，Created by Administrator on 2016/5/12.
 */
public class NewAccidentLoadPicView extends LFView implements View.OnClickListener, ILSMsgListener,
        MainActivity.OnActivityReturnBitmap, AdapterView.OnItemClickListener, ILFMsgListener {

    public static int DSIZE = 6;//默认总数目

    public static int ASIZE = 10;//补拍总数目

    private Context context;
    private View view;
    private GridView mGridView;
    private Button mBtn;
    private String caseNo;
    private BaseApplication mApplication;
    private EntityBean[] unqualifylist;//审核失败的图片集合
    private EntityBean[] isqualifylist;//审核通过的图片集合
    private int fromWhere;//0是正常的跳转，1是照片审核后跳转来的,审核后过来的，要将已经上传成功的照片展示出来
    private List<EntityBean> picLists;//显示的图片集合
    private AccidentLoadPicAdapter picAdapter;
    private EntityBean curBean;//当前点击的选项
    private boolean isSuccess = false;//上传是否成功
    private Dialog processDialog;
    private PromptDialog dialog;
    private String isSingle;
    private boolean isHistroy = false;

    private static final int SUCCESS = 0;

    private static final int FAIL = 1;

    private View curView;//准备刷新的view

    private int curPos;

    public NewAccidentLoadPicView(Context c, String caseNo, int fromWhere) {
        super(c);
        this.context = c;
        this.caseNo = caseNo;
        this.mApplication = ((MainActivity) c).getAppData();
        this.fromWhere = fromWhere;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    public void setUnqualifylist(EntityBean[] unqualifylist) {
        this.unqualifylist = unqualifylist;
    }

    public void setIsqualifylist(EntityBean[] isqualifylist) {
        this.isqualifylist = isqualifylist;
    }

    public void setIsHistroy(boolean isHistroy) {
        this.isHistroy = isHistroy;
    }

    //设置事故时单车还是双车类型
    public void setCaseType(String isSingle) {
        this.isSingle = isSingle;
        if (TextUtils.equals(isSingle, "0")) {//单车
            DSIZE = 3;
        } else if (TextUtils.equals(isSingle, "1")) {//双车
            DSIZE = 6;
        }
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initViews();
        initValues();
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (view == null) {
                return;
            }
            Bundle data = msg.getData();
            String path = data.getString("path");
            switch (msg.what) {
                case SUCCESS://图片上传成功
                    String type = curBean.getString("type");
                    if (TextUtils.equals(type, "-1")) {
                        curBean = new EntityBean();//补拍照片
                        curBean.set("type", "20");
                        picLists.add(picLists.size() - 1, curBean);
                    }
                    CommontUtils.deleteFile(curBean.getString("path"));//删除之前拍的图片
                    curBean.set("path", path);
                    if (picLists.size() > (ASIZE + DSIZE)) {
                        //拍照数目已达上限则移除+号项
                        picLists.remove(picLists.size() - 1);
                    }
                    picAdapter.updateItem(curPos, curView);
                    break;
                case FAIL://上传失败则显示重试对话框
                    String content = data.getString("content");
                    EntityBean bean = (EntityBean) data.getSerializable("data");
                    showRetryDialog(path, content, bean);
                    break;
                default:
                    break;
            }
        }
    };

    //弹出照片上传正常的dialog
    private void showNext() {
        String title = "事故照片上传成功，请进入下一步。";
        UiUtils.showDialog(context, null, null, title, "返回", "确认",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        return;
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AccidentCheckView accidentcheckview = new AccidentCheckView(context, caseNo, 0);
                        FrameworkManager.getInstance().showNewForm(context, accidentcheckview);
                        isSuccess = false;
                    }
                });
    }

    //验证图片是否全部上传
    private void checkImg() {
        String uid = mApplication.getKckpName();
        String token = mApplication.getToken();
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(context).checkImgIsOver(uid, token, "1", caseNo, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(context, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals("1", restate)) {
                    if (fromWhere == 1 && !isHistroy) {//重拍成功
                        LSMsgCall(30, "takesuccess");
                        OnDestroy();
                        closeForm();
                        isSuccess = false;
                    } else {
                        isSuccess = true;
                        showNext();
                    }
                } else {
                    String error = bean.getString("redes");
                    if (!TextUtils.isEmpty(error)) {
                        UiUtil.showToast(context, error);
                    }
                }
            }
        });
    }

    //初始化事故布局及注册事件
    public void initViews() {
        if (context == null) {
            return;
        }
        view = LayoutInflater.from(context).inflate(R.layout.view_newaccident_loadpic, null);
        if (view == null) {
            return;
        }
        //标题栏
        TextView titleTV = (TextView) view.findViewById(R.id.tv_title);
        titleTV.setText("上传事故照片");
        view.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnDestroy();
                closeForm();
            }
        });
        mBtn = (Button) view.findViewById(R.id.btn_dcqz);
        mGridView = (GridView) view.findViewById(R.id.newaccident_loadpic_gridview);
        picAdapter = new AccidentLoadPicAdapter(context);
        picAdapter.setIsSingle(isSingle);
        mGridView.setAdapter(picAdapter);

        //统计区分
        String text = context.getResources().getString(R.string.accident_load);
        mBtn.setText(CommontUtils.changeStrColor(text, "上传", Color.WHITE));

        regEvent(true);
    }

    private void initValues() {
        if (picLists == null) {
            picLists = new ArrayList<EntityBean>();
        } else {
            picLists.clear();
        }
        if (fromWhere == 1) {//审核失败重拍
            if (null != isqualifylist) {//通过的图片
                for (int i = 0; i < isqualifylist.length; i++) {
                    EntityBean bean = new EntityBean();
                    String imagetype = (String) isqualifylist[i].get("imagetype");
                    String imageurl = (String) isqualifylist[i].get("imageurl");
                    bean.set("type", imagetype);
                    bean.set("url", imageurl);
                    picLists.add(bean);
                    bean = null;
                }
            }
            if (null != unqualifylist) {//不通过的图片
                for (int i = 0; i < unqualifylist.length; i++) {
                    EntityBean bean = new EntityBean();
                    int imagetype = (int) unqualifylist[i].get("imagetype");
                    bean.set("type", imagetype);
                    picLists.add(bean);
                    bean = null;
                }
            }
            //按照图片类型排序
            Collections.sort(picLists, new Comparator<EntityBean>() {
                @Override
                public int compare(EntityBean lhs, EntityBean rhs) {
                    Integer lType = Integer.valueOf(lhs.getString("type"));
                    Integer rType = Integer.valueOf(rhs.getString("type"));
                    return lType.compareTo(rType);
                }
            });
        } else if (fromWhere == 0) {//拍摄事故照片
            for (int i = 0; i < DSIZE; i++) {
                EntityBean bean = new EntityBean();
                bean.set("type", i);
                picLists.add(bean);
                bean = null;
            }
        }
        if (picLists.size() < (DSIZE + ASIZE)) {//添加默认的+号图标
            EntityBean bean = new EntityBean();
            bean.set("type", "-1");
            picLists.add(bean);
            bean = null;
        }
        picAdapter.setLists(picLists);
        picAdapter.notifyDataSetChanged();
    }

    private void regEvent(boolean b) {
        if (mBtn != null) {
            mBtn.setOnClickListener(b ? this : null);
        }
        if (null != mGridView) {
            mGridView.setOnItemClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
            this.addILFMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
            this.removeILFMsgListener(this);
        }
    }


    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_dcqz:
                if (isSuccess) {
                    showNext();
                    return;
                }
                if (!checkTakePhoto()) {
                    UiUtil.showToast(getContext(), "请您拍摄完照片后进行下一步");
                    return;
                }
                checkImg();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        curBean = picLists.get(position);
        curView = view;
        curPos = position;
        String url = curBean.getString("url");
        if (!TextUtils.isEmpty(url)) {
            UiUtil.showToast(context, "本张照片已经审核通过，不需要重新拍摄！");
            return;
        }
        String type = curBean.getString("type");
        if (TextUtils.equals(type, "-1")) {//点击的+号图标
            if (picLists.size() > (DSIZE + ASIZE)) {
                UiUtil.showToast(context, "拍照数目已达上限！");
                return;
            }
        }
        //启动相机拍照
        String title = null;
        int resId = -1;
        switch (Integer.valueOf(type)) {
            case 0:
                if (TextUtils.equals(isSingle, "0")) {//单车
                    title = "车辆侧前方";
                    resId = R.drawable.car_6;
                } else {
                    title = "车头前方照片";
                    resId = R.drawable.car_4;
                }
                getCamera(title, "(请确保道路标线在拍摄画面中。)", resId);
                break;
            case 1:
                if (TextUtils.equals(isSingle, "0")) {//单车
                    title = "车辆侧后方";
                    resId = R.drawable.car_7;
                } else {
                    title = "车尾后方照片";
                    resId = R.drawable.car_3;
                }
                getCamera(title, "(请确保道路标线在拍摄画面中。)", resId);
                break;
            case 2:
                if (TextUtils.equals(isSingle, "0")) {
                    title = "车辆受损部位";
                    resId = R.drawable.car_8;
                } else {
                    title = "车辆受损部位照片";
                    resId = R.drawable.car_5;
                }
                getCamera(title, null, resId);
                break;
            case 3:
                getCamera("事故侧方全景照片", null, R.drawable.car_10);
                break;
            case 4:
                getCamera("对方驾驶证", null, R.mipmap.jsz_4);
                break;
            case 5:
                getCamera("对方行驶证", null, R.mipmap.xsz_5);
                break;
            default:
                getCamera("其他定责照片", null, 0);
                break;
        }
    }

    //启动相机
    public void getCamera(String title, String titleBottom, int resourceId) {
        if (!PermissionHelper.checkCameraPermissions(context)) {
            return;
        }
        Intent intent = new Intent(getContext(), HeNanSurfaceViewCameraActivity.class);
        Bundle bundle = new Bundle();

        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        if (!StringUtils.isEmpty(titleBottom)) {
            bundle.putString("titleBottom", titleBottom);
        }

        if (resourceId != 0) {
            bundle.putInt("backGroundResourceId", resourceId);
        }
        intent.putExtras(bundle);

        if (context instanceof MainActivity) {
            ((MainActivity) context).startActivityForResult(intent, 110);
        }
    }

    /**
     * 获取图片上传需要的实体参数
     */
    private EntityBean getEntityBean(String filePath, int currentImageType) {
        EntityBean bean = new EntityBean();
        bean.set("appcaseno", caseNo);
        bean.set("imagelon", mApplication.getLongitude());
        bean.set("imagelat", mApplication.getLatitude());
        bean.set("imageaddress", mApplication.getAddress());
        // 获取图片参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        bean.set("imagebig", new File(filePath).length());
//        bean.set("imageurl", FileUtils.File2byte(new File(filePath), false));
        bean.set("imagewide", Integer.toString(options.outWidth));
        bean.set("imageheigth", Integer.toString(options.outHeight));

        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        String phoneNumber = userinfo.getString("mobilephone");
        if (!StringUtils.isEmpty(phoneNumber)) {
            bean.set("casetelephoe", phoneNumber);
        }
        //拍照类型
        bean.set("shoottype", "1");//1是定责照片，2是定损照片
        bean.set("imagetype", currentImageType);
        bean.set("imagedate", CommontUtils.getNowTime());
        bean.set("areaid", mApplication.getAreaid());
        bean.set("uid", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        return bean;
    }

    /**
     * 异步上传图片
     *
     * @param picBean
     */
    private void useLoadingPic(final EntityBean picBean, final String path) {
        ApiImpI.getInstance(context.getApplicationContext()).uploadFile(picBean, "2", path, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                if (null != processDialog && processDialog.isShowing()) {
                    processDialog.dismiss();
                }
                if (null != myHandler && !TextUtils.isEmpty(error)) {
                    myHandler.sendMessage(getMsg(FAIL, path, error, picBean));
                }
            }

            @Override
            public void onSuccess(Object result) {
                if (null != processDialog && processDialog.isShowing()) {
                    processDialog.dismiss();
                }
                if (result != null) {
                    EntityBean bean = (EntityBean) result;
                    if (bean != null) {
                        String restate = bean.getString("restate");
                        if ("1".equals(restate)) {
                            if (null != myHandler) {
                                myHandler.sendMessage(getMsg(SUCCESS, path, null, null));
                            }
                        } else {
                            if (null != myHandler) {
                                String redes = bean.getString("redes");
                                myHandler.sendMessage(getMsg(FAIL, path, redes, picBean));
                            }
                        }
                    }
                }
            }
        });
    }

    private Message getMsg(int what, String path, String content, EntityBean picBean) {
        Message msg = Message.obtain();
        msg.what = what;
        Bundle bundle = new Bundle();
        bundle.putString("path", path);
        bundle.putString("content", content);
        bundle.putSerializable("data", picBean);
        msg.setData(bundle);
        return msg;
    }

    //显示重试对话框
    private void showRetryDialog(String path, String content, EntityBean bean) {
        if (null == dialog) {
            dialog = new PromptDialog(context);
            dialog.setIcon(R.mipmap.warn);
            dialog.setCancel("返回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setConfirm("重试", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EntityBean tagBean = (EntityBean) v.getTag(R.id.tag_first);
                    String tagPath = (String) v.getTag(R.id.tag_second);
                    dialog.dismiss();
                    processDialog.show();
                    useLoadingPic(tagBean, tagPath);
                }
            });
        }
        dialog.setConfirmTag(R.id.tag_first, bean);
        dialog.setConfirmTag(R.id.tag_second, path);
        dialog.setInfo(content);
        dialog.show();
    }

    @Override
    public Object onLSMsg(int code, Object... arg1) {
        switch (code) {
            case MsgConstant.FINSHTAKEPHOTO:
                OnDestroy();
                closeForm();
                break;
            default:
                break;
        }
        return null;
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {//点击返回按键
            if (fromWhere == 1 && !isHistroy) {//重拍
                if (checkTakePhoto()) {
                    checkImg();
                    return false;
                }
            }
            OnDestroy();
            closeForm();
        }
        return null;
    }

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            String path = bundle.getString("image");
            if (path == null) {
                UiUtil.showToast(context, "照片拍摄失败！");
                return;
            }
            if (null == curBean) {
                return;
            }
            String type = curBean.getString("type");
            if (TextUtils.equals(type, "-1")) {
                type = "20";//补拍的照片类型
            }
            //照片拍完后立即上传
            if (processDialog == null) {
                processDialog = UiUtils.showProcessDialogPro(getContext(), "正在上传");
            } else {
                processDialog.show();
            }
            useLoadingPic(getEntityBean(path, Integer.valueOf(type)), path);
        }
    }

    /**
     * 验证图片是否拍摄
     *
     * @return
     */
    private boolean checkTakePhoto() {
        int size = picLists.size();
        if (size < (DSIZE + 1)) {
            return false;
        }
        for (int i = 0; i < size; i++) {
            EntityBean bean = picLists.get(i);
            String type = bean.getString("type");
            if (!TextUtils.equals(type, "-1")) {
                String url = bean.getString("url");
                String path = bean.getString("path");
                if (TextUtils.isEmpty(url) && TextUtils.isEmpty(path)) {//照片未拍摄
                    return false;
                }
            }
        }
        return true;
    }


    @Override
    public void OnDestroy() {
        super.OnDestroy();
        regEvent(false);
        if (null != unqualifylist) {
            unqualifylist = null;
        }
        if (null != isqualifylist) {
            isqualifylist = null;
        }
        if (null != picLists) {
            for (int i = 0; i < picLists.size(); i++) {//销毁无用的照片文件
                String path = picLists.get(i).getString("path");
                CommontUtils.deleteFile(path);
            }
            picLists.clear();
            picLists = null;
        }
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        if (null != dialog) {
            dialog.dismiss();
            dialog = null;
        }
        picAdapter = null;
        if (mGridView != null) {
            mGridView.setAdapter(null);
            mGridView = null;
        }
        myHandler = null;
        view = null;
    }
}